import json
import logging
import re

from django.contrib.auth import login, authenticate
from django.http import JsonResponse
from django.shortcuts import render
from django.views import View
from random import randint
from django_redis import get_redis_connection

from apps.answer.models import Label, Question, Reply
from apps.found_person.models import Enterprise, Recruit
from apps.news.models import Article
from apps.users.models import User
from celery_tasks.sms.tasks import send_code
from tenfold_pro import settings
from utils.login import loginrequired
from utils.shenhe import text, tupian
from utils.token_jwt import generate_tokens, check_token


# Create your views here.

# 短信验证码
class Sms_Codes(View):
    def get(self,request,mobile):
        # 获取六位短信验证码
        code = randint(100000,999999)

        # 获取查看redis里面是否有验证码
        redis = get_redis_connection('code')
        code_sms = redis.get(mobile)
        if code_sms:
            # 有就返回短信验证码已发送
            return JsonResponse({'success':False,'message':'短信验证码已发送'})
        try:
            # 调用阿里云向用户手机号发送短信验证码
            # send_code.delay(mobile,code)
            # 把短信验证码保存在redis
            redis.setex(mobile, 300, code)
        except Exception as e:
            logger = logging.getLogger('django')
            logger.info(e)
            return JsonResponse({'success':False,'message': '短信验证码发送失败'})
        # 返回结果
        return  JsonResponse({'success':True, 'message':'OK','sms_code':code})

# 注册
class Register(View):
    def post(self,request):
        # 提取前端获取到的参数
        content_type = request.META.get('CONTENT_TYPE')
        data = json.loads(request.body)
        username = data.get('username')
        password = data.get('password')
        mobile = data.get('mobile')
        sms_code = data.get('sms_code')

        # 审核用户名是否合规
        wenben = text(username)
        if wenben.get('conclusion') == '不合规':
            return JsonResponse({'success':False, 'message':wenben.get('data')[0].get('msg')})

        # 判断用户名是否存在
        count = User.objects.filter(username=username).count()
        if count != 0:
            return JsonResponse({'success': False, 'message': '用户名已存在'})

        # 判断手机号是否合法
        if not re.match(r'^1[3-9]\d{9}$', mobile):
            return JsonResponse({'success': False, 'message': '手机格式有误!'})

        # 判断密码是否是8-20个数字或字符
        if not re.match(r'^[0-9A-Za-z]{6,16}$', password):
            return JsonResponse({'success': False, 'message': '请输入6 - 16!位的密码（数字 + 字母）'})

        # 判断手机号是否存在
        count = User.objects.filter(mobile=mobile).count()
        if count != 0:
            return JsonResponse({'success': False, 'message': '手机号已存在'})

        # 从redis获取短信验证码
        redis = get_redis_connection('code')
        code = redis.get(mobile)

        # 判断短信验证码是否有误
        try:
            if code.decode() != sms_code:
                return JsonResponse({'success': False, 'message': '短信验证码有误'})
        except Exception as e:
            logger = logging.getLogger('django')
            logger.info(e)
            return JsonResponse({'success': False, 'message': '短信验证码有误'})

        # 把用户信息存入数据库
        try:
            user = User.objects.create_user(
                username=username,
                nickname=username,
                mobile=mobile,
                password=password,
                avatar='01786557e4a6fa0000018c1bf080ca.png@1280w_1l_2o_100sh.png',
            )
        except Exception as e:
            logger = logging.getLogger('django')
            logger.info(e)
            return JsonResponse({'success': False, 'message': '注册错误'})

        # 短信验证码一致就删除数据库的短信验证码
        redis.delete(mobile)

        # 状态保持
        login(request, user)
        token = generate_tokens(user.id)

        return JsonResponse({
            'success': True,
            'message': 'OK',
            'token': token,
            'id': user.id,
            'username':user.username,
            'mobile':user.mobile,
            'avatar': 'http://s7g9jujrf.hn-bkt.clouddn.com/' + str(user.avatar)
        })

# 登录
class Login(View):
    def post(self,request):
        content_type = request.META.get('CONTENT_TYPE')
        data = json.loads(request.body)
        username = data.get('username')
        password = data.get('password')
        # 判断是否缺少参数
        if not all(['mobile', 'phonecode', 'password']):
            return JsonResponse({'success': False, 'message': '缺少参数'})

        if not re.match(r'^1[3-9]\d{9}$', username):
            return JsonResponse({'success': False, 'message': '手机格式有误!'})

        # 判断该用户是否存在
        User.USERNAME_FIELD = 'mobile'
        user = authenticate(username=username, password=password)
        if not user:
            return JsonResponse({'success': False, 'message': '手机号或密码有误!'})

        # 状态保持
        login(request, user)
        token = generate_tokens(user.id)

        return JsonResponse({
            'success': True,
            'message': 'OK',
            'token': token,
            'id': user.id,
            'username': user.username,
            'mobile': user.mobile,
            'avatar': 'http://s7g9jujrf.hn-bkt.clouddn.com/' + str(user.avatar)
        })



class UserInfo(View):
    # 个人中心
    @loginrequired
    def get(self,request):
        # 获取保存到全局变量的用户信息
        user = request.user

        # 查询用户的擅长技术
        labels = []
        for i in Label.objects.filter(users=user.id).all():
            labels.append({'label_name':i.label_name})
        questions = []
        for i in Question.objects.filter(user=user.id).all():
            questions.append({
                'title': i.title,
                'useful_count':i.useful_count,
                'createtime':i.createtime,
            })
        answer_question = []
        for i in Reply.objects.filter(user=user.id).all():
            answer_question.append({
                'content': i.content,
                'useful_count':i.useful_count,
                'createtime':i.createtime,
            })
        collected_articles = []
        for i in Article.objects.filter(user=user.id).all():
            collected_articles.append({
                'title': i.title,
            })
        enterpises = []
        for i in Enterprise.objects.filter(users=user.id).all():
            recruits = []
            for j in Recruit.objects.filter(enterprise=i.id).all():
                recruits.append({
                    'jobname':j.jobname
                })
            enterpises.append({
                'id': i.id,
                'name': i.name,
                'labels': i.labels,
                'logo': 'http://s7g9jujrf.hn-bkt.clouddn.com/' + str(i.logo),
                'recruits': recruits,
                'summary': i.summary,
            })

        return JsonResponse({
            'code': 0,
            'message': 'OK',
            'id': user.id,
            'username': user.username,
            'mobile': user.mobile,
            'avatar': 'http://s7g9jujrf.hn-bkt.clouddn.com/' + str(user.avatar),
            'realname': user.realname,
            'birthday':user.birthday,
            'sex':user.sex,
            'website':user.website,
            'email':user.email,
            'city':user.city,
            'address':user.address,
            'labels':labels,
            'questions':questions,
            'answer_question':answer_question,
            'collected_articles':collected_articles,
            'enterpises':enterpises,
        })
       # 修改用户信息
    @loginrequired
    def put(self, request):
        user = request.user

        content_type = request.META.get('CONTENT_TYPE')
        data = json.loads(request.body)
        realname = data.get('realname')
        sex = data.get('sex')
        birthday = data.get('birthday')
        website = data.get('website')
        mobile = data.get('mobile')
        email = data.get('email')
        city = data.get('city')
        address = data.get('address')
        avatar = data.get('avatar')
        # 审核用户名是否合规
        wenben = text(realname)
        if wenben.get('conclusion') == '不合规':
            return JsonResponse({'success': False, 'message': wenben.get('data')[0].get('msg')})

        # 判断手机号是否合法
        if not re.match(r'^1[3-9]\d{9}$', mobile):
            return JsonResponse({'success': False, 'message': '手机格式有误!'})

        # 判断邮箱是否合法
        if not re.match(r'([A-Za-z0-9]+[.-_])*[A-Za-z0-9]+@[A-Za-z0-9-]+(\.[A-Z|a-z]{2,})+', email):
            return JsonResponse({'success': False, 'message': '邮箱格式有误!'})

        # 判断登录用户的头像是否合规
        avater_data = tupian('http://s7g9jujrf.hn-bkt.clouddn.com/' + avatar)
        if avater_data.get('conclusion') == '不合规':
            return JsonResponse({'success': False, 'errmsg': avater_data.get('data')[0].get('msg')})



        # 更新用户信息
        try:
            userinfo = User.objects.filter(id=user.id).update(
                realname=realname,
                sex=sex,
                birthday=birthday,
                website=website,
                mobile=mobile,
                email=email,
                city=city,
                address=address,
                avatar=avatar.split("/")[3],
            )

        except Exception as e:
            logger = logging.getLogger('django')
            logger.info(e)
            return JsonResponse({'success': False, 'message': '保存失败!'})
        userinfo = User.objects.filter(id=user.id).first()
        # 查询登录用户的擅长技术
        labels = []
        for i in Label.objects.filter(users=userinfo.id).all():
            labels.append({'label_name': i.label_name})

        # 查询登录用户的提问
        questions = []
        for i in Question.objects.filter(user=userinfo.id).all():
            questions.append({
                'title': i.title,
                'useful_count': i.useful_count,
                'createtime': i.createtime,
            })

        # 查询登录用户的回答
        answer_question = []
        for i in Reply.objects.filter(user=userinfo.id).all():
            answer_question.append({
                'content': i.content,
                'useful_count': i.useful_count,
                'createtime': i.createtime,
            })

        # 查询登录用户的收藏文章
        collected_articles = []
        for i in Article.objects.filter(user=userinfo.id).all():
            collected_articles.append({
                'title': i.title,
            })

        # 查询登录用户的收藏企业
        enterpises = []
        for i in Enterprise.objects.filter(users=userinfo.id).all():
            recruits = []
            # 查询登陆用户的收藏企业里面招聘的职位
            for j in Recruit.objects.filter(enterprise=i.id).all():
                recruits.append({
                    'jobname': j.jobname
                })
            enterpises.append({
                'id': i.id,
                'name': i.name,
                'labels': i.labels,
                'logo': 'http://s7g9jujrf.hn-bkt.clouddn.com/' + str(i.logo),
                'recruits': recruits,
                'summary': i.summary,
            })

        return JsonResponse({
            'code': 0,
            'message': 'OK',
            'id': userinfo.id,
            'username': userinfo.username,
            'mobile': userinfo.mobile,
            'avatar': 'http://s7g9jujrf.hn-bkt.clouddn.com/' + str(userinfo.avatar),
            'realname': userinfo.realname,
            'birthday': userinfo.birthday,
            'sex': userinfo.sex,
            'website': userinfo.website,
            'email': userinfo.email,
            'city': userinfo.city,
            'address': userinfo.address,
            'labels': labels,
            'questions': questions,
            'answer_question': answer_question,
            'collected_articles': collected_articles,
            'enterpises': enterpises,
        })

# 修改用户头像
class Avatar(View):
    def post(self,request):
        user = request.user
        # 获取前端数据
        avatar = request.FILES.get('img')
        import imghdr
        if not imghdr.what(avatar):
            return {'errno': '400', 'errmsg': '文件格式不正确'}

        from utils.qiniu_upload import qiniu_upload
        # 上传头像并获取头像的地址
        result = qiniu_upload(avatar)
        image_avatar = result.get('key')
        return JsonResponse({'errno': '0', 'errmsg': 'OK', 'imgurl': 'http://s7g9jujrf.hn-bkt.clouddn.com/' + image_avatar})

# 修改用户密码
class Password(View):
    @loginrequired
    def put(self,request):
        user = request.user

        content_type = request.META.get('CONTENT_TYPE')
        data = json.loads(request.body)
        password = data.get('password')
        # 判断密码是否是8-20个数字或字符
        if not re.match(r'^[0-9A-Za-z]{6,16}$', password):
            return JsonResponse({'code': 400, 'message': '请输入6 - 16!位的密码（数字 + 字母）'})
        # 修改用户密码
        try:
            request.user.set_password(password)
            request.user.save()
        except Exception as e:
            return JsonResponse({'success': False, 'message': '保存失败!'})
        # 清理状态保持信息
        # logout(request)
        return JsonResponse({'code': '0', 'errmsg': 'OK', 'password': password})